// https://echarts.apache.org/zh/option.html#series-scatter.data

import React, { useState, useEffect, useRef, useMemo } from 'react'
import Echarts from 'echarts';
import style from './ChiShuMai.module.scss'

// 图表初始化配置
const option = {
    tooltip: {
        position: 'top',
    },
    grid: {
        right: '13%',
        bottom: '10%'
    },
    xAxis: {
        name: '时间',
        boundaryGap: true,
        splitLine: {
            show: false
        },
    },
    yAxis: {
        name: '脉位',
        max: 3.5,
        min: .5,
        minInterval: 1,
        axisLabel: {
            formatter: v => {
                switch (v) {
                    case 1:
                        return '寸  ';
                    case 2:
                        return '关  ';
                    case 3:
                        return '尺  ';
                    default:
                        return ''
                }
            }
        },
        splitLine: {
            show: false
        },
        axisLine: {
            show: true
        }
    },
    series: [{
        name: '',
        type: 'scatter',
        data: [],
        markLine: {
            lineStyle: {
                color: 'pink'
            },
            data: [[{
                coord: [-.15, .5],
                symbol: 'none'
            }, {
                coord: [-.15, 3.5],
                symbol: 'none'
            }]]
        },
        animationDurationUpdate: 500,
        animationEasing: 'linear',
    }]
}
let timer // 定时器，放在外面方便清除

export default function ChiShuMai(params) {
    const [chart, setChart] = useState()
    const [timeRange, setTimeRange] = useState(8)
    const [type, setType] = useState(0)
    const pulseRates = [
        [90, 75, 60],
        [60, 120, 60],
        [90, 90, 90]
    ]
    const [cun, setCun] = useState(pulseRates[0][0])
    const [guan, setGuan] = useState(pulseRates[0][1])
    const [chi, setChi] = useState(pulseRates[0][2])
    const [opt, setOpt] = useState(option)
    const getPoints = (num, y, pauseNum) => { // 通过脉率获取分布的点


        const step = 60 / num
        let arr = []
        let x = 0
        while (x < timeRange - .2) {
            let color = y === 1 ? 'rgba(255,100,100,.5)' : y === 2 ? 'rgba(255,10,10,.7)' : '#ca0000'
            debugger
            if (type === 2) { // 关数寸尺促
                const rdm = Math.random()
                pauseNum = rdm < .9 ? pauseNum :pauseNum + 1
                const remainder = x / step % pauseNum // 余数
                color = (pauseNum - remainder < .0001 || remainder === 0) && y !== 2 ? 'rgba(0,0,0,0)' : color
            }
            arr.push({
                value: [Number(x.toFixed(2)), y, 0],
                itemStyle: { color }
            })
            x += step
        }
        return arr
    }
    const pointsCun = useMemo(() => getPoints(cun, 1, Math.random() < 0.5 ? 3 : 4), [timeRange, type, cun, guan, chi])
    const pointsGuan = useMemo(() => getPoints(guan, 2))
    const pointsChi = useMemo(() => getPoints(chi, 3, Math.random() < 0.5 ? 4 : 3), [timeRange, type, chi])
    const getOpt = useRef()

    let i = 0
    useEffect(() => {
        getOpt.current = () => opt
    });
    useEffect(() => {
        setCun(pulseRates[type][0])
        setGuan(pulseRates[type][1])
        setChi(pulseRates[type][2])
    }, [type, timeRange]);

    useEffect(() => {
        const opt = getOpt.current()
        opt.series[0].data = [...pointsCun, ...pointsGuan, ...pointsChi]
    }, [cun, guan, chi]);

    // 图表更新动画
    const run = () => {
        const opt = getOpt.current()
        if (!opt) return
        // 点缩放
        const data0 = opt.series[0].data.map(item => {
            if (item.value[0] < i) {
                return {
                    ...{
                        ...item,
                        symbolSize: (i - item.value[0]) < .51 ? 25 : 8,
                    }
                }
            } else {
                return item
            }
        })
        // 时间线移动
        let markLine0 = opt.series[0].markLine
        markLine0.data[0][0].coord[0] += .2
        markLine0.data[0][1].coord[0] += .2

        setOpt({ ...opt, series: [{ data: data0, markLine: markLine0 }] })
    }
    // 启动
    const start = () => {
        i = 0
        const opt = getOpt.current()
        let markLine0 = opt.series[0].markLine
        markLine0.data[0][0].coord[0] = -.15
        markLine0.data[0][1].coord[0] = -.15
        opt.series[0].data = [...pointsCun, ...pointsGuan, ...pointsChi]
        setOpt(opt)
        clearInterval(timer)
        timer = setInterval(() => {
            if (i < timeRange) {
                run()
                i += .2
            } else {
                clearInterval(timer)
            }
        }, 200)
    }

    // 挂载后
    useEffect(() => {
        setChart(Echarts.init(document.querySelector('#chart_chiShuMai')))
        start()
    }, [])

    // 刷新图表
    useEffect(() => {
        if (!chart) return
        chart.setOption(opt)
    }, [chart, opt]);

    return <div className={style['m-chiShuMai']}>
        <h2>迟数脉区分寸关尺示意图</h2>
        <div id='chart_chiShuMai' />
        <div className={'inputs'}>
            <div className={'ranges'} disable>
                <label>尺<input disabled={type} type='range' min='40' max='120' value={chi} onChange={e => setChi(e.target.value)} />{chi}次/分</label><br />
                <label>关<input disabled={type} type='range' min='40' max='120' value={guan} onChange={e => setGuan(e.target.value)} />{guan}次/分</label><br />
                <label>寸<input disabled={type} type='range' min='40' max='120' value={cun} onChange={e => setCun(e.target.value)} />{cun}次/分</label><br />
                <label>时间<input type='range' min='2' max='20' value={timeRange} onChange={e => { setTimeRange(e.target.value); start() }} />{timeRange}秒</label>
            </div>
            <div className={'radios'}>
                <label><input type="radio" name='type' checked={type === 0} onChange={e => setType(0)} />寸关尺脉率自由</label>
                <label><input type="radio" name='type' checked={type === 1} onChange={e => setType(1)} />关数寸尺迟</label>
                <label><input type="radio" name='type' checked={type === 2} onChange={e => setType(2)} />关数寸尺促</label>
            </div>

        </div>
        <div>
            <button onClick={start}>开始</button>
            <button onClick={() => clearInterval(timer)}>暂停</button>
        </div>

    </div>
}